0001    //
0002    //  BigUInt Square Root.swift
0003    //  BigInt
0004    //
0005    //  Created by Károly Lőrentey on 2016-01-03.
0006    //  Copyright © 2016 Károly Lőrentey. All rights reserved.
0007    //
0008    
0009    import Foundation
0010    
0011    //MARK: Square Root
0012    
0013    /// Returns the integer square root of a big integer; i.e., the largest integer whose square isn't greater than `value`.
0014    ///
0015    /// - Returns: floor(sqrt(value))
0016    @warn_unused_result
0017    public func sqrt(value: BigUInt) -> BigUInt {
0018        // This implementation uses Newton's method.
0019        guard !value.isZero else { return BigUInt() }
0020        var x = BigUInt(1) << ((value.width + 1) / 2)
0021        while true {
0022            let y = (x + value / x) >> 1
0023            if x == y || x == y - 1 { break }
0024            x = y
0025        }
0026        return x
0027    }
0028    
0029